package com.catcoin.hhtb.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.catcoin.hhtb.model.Account;
import com.catcoin.hhtb.model.Hhtbusers;
import com.catcoin.hhtb.model.LogHhtbe;
import com.catcoin.hhtb.model.SysConfigs;
import com.catcoin.hhtb.result.AppResult;
import com.catcoin.hhtb.result.Result;
import com.catcoin.hhtb.service.DepfeignInterface;
import com.catcoin.hhtb.service.IAccountService;
import com.catcoin.hhtb.service.IHhtbusersService;
import com.catcoin.hhtb.service.ToolfeignInterface;
import com.catcoin.hhtb.service.impl.SysConfigsServiceImpl;
import com.catcoin.hhtb.util.StringUtils;
import org.springframework.amqp.core.AmqpTemplate;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

@RestController
@CrossOrigin
public class HhtbController {

    @Autowired
    private ToolfeignInterface toolfeignInterface;

    @Autowired
    private IAccountService accountService;

    @Autowired
    private IHhtbusersService hhtbusersService;

    @Autowired
    private DepfeignInterface depfeignInterface;

    @Autowired
    private SysConfigsServiceImpl sysConfigsService;

    @Autowired
    private AmqpTemplate rabbitTemplate;


    @RequestMapping(value = "/hhtb")
    public Object hhtb(){
        return "hhtb";
    }

    /**
     *交易所HHTB充值
     * 减少账户表的值，增加交易所HHTB的值
     * @param userId
     * @param cash
     * @return
     */
    @RequestMapping(value = "/addHhtb")
    public Object addHhtb(String userId,BigDecimal cash){
        if (cash.compareTo(BigDecimal.ZERO) <= 0){
            return AppResult.ERROR("请输入正确的金额！");
        }
        Account account = new Account();
        account.setUserId(Integer.parseInt(userId));
        EntityWrapper<Account> ew = new EntityWrapper<Account>(account);
        account = accountService.selectOne(ew);
        BigDecimal acash = account.getCash();
        if(acash.compareTo(cash)< 0){
            return AppResult.ERROR("HHTB充值金额不能大于账户余额！");
        }
        account.setCash(acash.subtract(cash));

        AppResult appResult = this.getUserID(Integer.parseInt(userId));
        if (appResult.getStatus()==-1){
            return appResult;
        }
        String userID = appResult.getData().toString();
        SysConfigs sysConfigs = new SysConfigs();
        sysConfigs.setFieldCode("hhtbRate");
        EntityWrapper<SysConfigs> entityWrapper = new EntityWrapper<SysConfigs>(sysConfigs);
        sysConfigs = sysConfigsService.selectOne(entityWrapper);
        BigDecimal bigDecimal  =  new BigDecimal(sysConfigs.getFieldValue());
        BigDecimal amount = cash.divide(bigDecimal,8,BigDecimal.ROUND_DOWN);
        /**
         * 获取交易所余额
         */
        String coinID = "21";
        String result =  toolfeignInterface.getBalance(userID,coinID);
        if ("error".equals(result)){
            return AppResult.ERROR("获取交易所余额失败");
        }
        JSONObject jsonObject = JSON.parseObject(result);

        BigDecimal  available = null;

        if (jsonObject.getString("des").toString().equals("success")){
            JSONObject  jsonObject1 = jsonObject.getJSONObject("datas");
            available  = new BigDecimal(jsonObject1.getString("available"));
        }else{
            return AppResult.ERROR("获取交易所余额失败");
        }
        try {
            toolfeignInterface.operate(userID,"17","1",amount.toString());
            /**
             * 如果调用交易所接口失败，不会执行数据库操作
             */
            accountService.updateById(account);
            /**
             * 消息队列发送日志信息
             */
            String remark = "hhtb充值的金额是"+amount;
            String orderNo = StringUtils.getOrderIdByTime("2");
            LogHhtbe logHhtbe = new LogHhtbe();
            logHhtbe.setUserId(Integer.parseInt(userId));
            logHhtbe.setFromId(Integer.parseInt(userId));
            logHhtbe.setOrderNo(orderNo);
            logHhtbe.setPreHHTBE(available);
            logHhtbe.setHhtbe(amount);
            logHhtbe.setHHTBEType(1);
            logHhtbe.setRemark(remark);
            logHhtbe.setDataFlag(1);
            logHhtbe.setCreateTime(new Date());
            logHhtbe.setType(0);
            JSONObject jsonObject1 = (JSONObject)JSONObject.toJSON(logHhtbe);
            String content = jsonObject1.toJSONString();
            rabbitTemplate.convertAndSend("loghhtbe",content);
            return AppResult.OK("冲币成功！");
        }catch (Exception e){
            /**
             * 失败日志
             */
            return  AppResult.ERROR("冲币失败！");
        }

    }

    /**
     * 用户提币
     * @param userId
     * @param hhtb
     * @return
     */
    @RequestMapping("/withdrawCash")
    public AppResult withdrawCash(String userId,BigDecimal hhtb){
        if (hhtb.compareTo(BigDecimal.ZERO) <= 0){
            return AppResult.ERROR("请输入正确的hhtb！");
        }
        Account account = new Account();
        account.setUserId(Integer.parseInt(userId));
        EntityWrapper<Account> ew = new EntityWrapper<Account>(account);
        account = accountService.selectOne(ew);
        /**
         * 获取交易所Id
         */
        AppResult appResult = this.getUserID(Integer.parseInt(userId));
        if (appResult.getStatus()==-1){
            return appResult;
        }
        String userID = appResult.getData().toString();
        /**
         * 计算出提币的金额（人民币）
         */
        SysConfigs sysConfigs = new SysConfigs();
        sysConfigs.setFieldCode("hhtbRate");
        EntityWrapper<SysConfigs> entityWrapper = new EntityWrapper<SysConfigs>(sysConfigs);
        sysConfigs = sysConfigsService.selectOne(entityWrapper);
        BigDecimal bigDecimal  =  new BigDecimal(sysConfigs.getFieldValue());
        BigDecimal cash = hhtb.multiply(bigDecimal);
        account.setCash(cash.add(account.getCash()));
        /**
         * 获取交易所余额
         */
        String coinID = "21";
        String result =  toolfeignInterface.getBalance(userID,coinID);
        if ("error".equals(result)){
            return AppResult.ERROR("获取交易所余额失败");
        }
        JSONObject jsonObject = JSON.parseObject(result);
        if (jsonObject.getString("des").toString().equals("success")){
            JSONObject  jsonObject1 = jsonObject.getJSONObject("datas");
            BigDecimal  available  = new BigDecimal(jsonObject1.getString("available"));
            if (available.compareTo(hhtb)<0){
                return AppResult.ERROR("hhtb余额不足，请重新输入hhtb金额");
            }
            try {
                toolfeignInterface.operate(userID,"17","0",hhtb.toString());
                accountService.updateById(account);
                /**
                 * 发送提币成功流水队列
                 */
                String remark = "hhtb提币的金额是"+hhtb;
                String orderNo = StringUtils.getOrderIdByTime("2");
                LogHhtbe logHhtbe = new LogHhtbe();
                logHhtbe.setUserId(Integer.parseInt(userId));
                logHhtbe.setFromId(Integer.parseInt(userId));
                logHhtbe.setOrderNo(orderNo);
                logHhtbe.setPreHHTBE(available);
                logHhtbe.setHhtbe(hhtb);
                logHhtbe.setHHTBEType(-1);
                logHhtbe.setRemark(remark);
                logHhtbe.setDataFlag(1);
                logHhtbe.setCreateTime(new Date());
                logHhtbe.setType(1);
                JSONObject jsonObject2 = (JSONObject)JSONObject.toJSON(logHhtbe);
                String content = jsonObject2.toJSONString();
                rabbitTemplate.convertAndSend("loghhtbe",content);
                return AppResult.OK("提币成功！");
            }catch (Exception e){
                /**
                 *发送提币失败流水队列
                 */
                return AppResult.OK("提币失败！");
            }


        }else {
            return AppResult.ERROR("获取交易所余额失败");
        }
    }


    /**
     * 获取交易所余额
     * @param userId
     * @param coinId
     * @return
     */
    @RequestMapping(value = "/getBalance")
    public Object getBalance(Integer userId, String coinId){

        Hhtbusers hhtbusers = new Hhtbusers();
        hhtbusers.setUserId(userId);
        EntityWrapper<Hhtbusers> ew = new EntityWrapper<Hhtbusers>(hhtbusers);
        hhtbusers = hhtbusersService.selectOne(ew);
        if (hhtbusers == null){
            return AppResult.ERROR("用户不存在");
        }
        String resultPhone = toolfeignInterface.register(hhtbusers.getUserPhone());
        if ("error".equals(resultPhone)){
            return AppResult.ERROR("获取余额失败");
        }
        JSONObject jsonObjectPhone = JSON.parseObject(resultPhone);
        if(jsonObjectPhone.getString("des").toString().equals("success")){
            JSONObject  jsonObject1 = jsonObjectPhone.getJSONObject("datas");
            String userID = jsonObject1.getString("userID");
            String coinID =  coinId;
            String result =  toolfeignInterface.getBalance(userID,coinID);
            if ("error".equals(result)){
                return AppResult.ERROR("获取余额失败");
            }
            JSONObject jsonObject = JSON.parseObject(result);
            if(jsonObject.getString("des").toString().equals("success")){
                SysConfigs sysConfigs = new SysConfigs();
                sysConfigs.setFieldCode("hhtbRate");
                EntityWrapper<SysConfigs> entityWrapper = new EntityWrapper<SysConfigs>(sysConfigs);
                sysConfigs = sysConfigsService.selectOne(entityWrapper);
                String values  =  sysConfigs.getFieldValue();
                String str  = "1HHTB="+values+"CNY";
                JSONObject jsonObject2  = jsonObject.getJSONObject("datas");
                jsonObject2.put("remark",str);
                return AppResult.OK(jsonObject2);
            }else{
                return AppResult.ERROR("获取余额失败");
            }
        }else{
            return AppResult.ERROR("获取交易所用户Id失败");
        }

    }

    /**
     * 通过app用户id获取交易所用户id
     * @param userId
     * @return
     */
    private AppResult getUserID(Integer userId){
        Hhtbusers hhtbusers = new Hhtbusers();
        hhtbusers.setUserId(userId);
        EntityWrapper<Hhtbusers> ew = new EntityWrapper<Hhtbusers>(hhtbusers);
        hhtbusers = hhtbusersService.selectOne(ew);
        if (hhtbusers == null){
            return AppResult.ERROR("用户不存在");
        }
        String resultPhone = toolfeignInterface.register(hhtbusers.getUserPhone());
        if ("error".equals(resultPhone)){
            return AppResult.ERROR("获取交易所用户Id失败");
        }
        JSONObject jsonObjectPhone = JSON.parseObject(resultPhone);
        if(jsonObjectPhone.getString("des").toString().equals("success")){
            JSONObject  jsonObject1 = jsonObjectPhone.getJSONObject("datas");
            String userID = jsonObject1.getString("userID");
            return AppResult.OK(userID);
        }else{
            return AppResult.ERROR("获取交易所用户Id失败");
        }
    }

    /**
     * 获取交易所用户ID
     * @param userMobile
     * @return
     */
    @RequestMapping(value = "/register")
    public Object register(String userMobile){
        String result = toolfeignInterface.register(userMobile);
        JSONObject jsonObject = JSON.parseObject(result);
        if(jsonObject.getString("des").toString().equals("success")){
            return AppResult.OK(jsonObject.getJSONObject("datas"));
        }else{
            return AppResult.ERROR("获取交易所用户Id失败");
        }
    }

    /**
     * 猫币复投
     * @param userId
     * @param amount
     * @return
     */
    @RequestMapping(value = "/operate")
    public Object operate(String userId,String amount){
        /**
         * 此处为减少交易所hhtb货币
         */
        String isBuy = "0";
        String coinID = "21";
        String result = toolfeignInterface.operate(userId,coinID,isBuy,amount);
        JSONObject jsonObject = JSON.parseObject(result);
        if(jsonObject.getString("des").toString().equals("success")){
//            Account account = new Account();
//            account.setUserId(Integer.parseInt(userId));
//            EntityWrapper<Account> entityWrapper = new EntityWrapper<Account>(account);
//            account = accountService.selectOne(entityWrapper);
//            if (account == null){
//                return Result.EEROR("用户未在app注册！");
//            }
//            BigDecimal bigDecimal = new BigDecimal(Integer.parseInt(amount));
//            account.setHhtbe(account.getHhtbe().add(bigDecimal));
//            accountService.updateById(account);
            BigDecimal jbhttb = new BigDecimal(amount);
            depfeignInterface.httbCVMaoBi(jbhttb,Integer.parseInt(userId));
            return AppResult.OK(jsonObject.getJSONObject("datas"));
        }else{
            return AppResult.ERROR("操作失败");
        }
    }

    @RequestMapping("/reCast")
    public Object reCast(Integer userId,BigDecimal jbhttb){
        return depfeignInterface.httbCVMaoBi(jbhttb,userId);
    }

    @RequestMapping("/getFunds")
    public AppResult getFunds(Integer userId,String coinId,String page){
        /**
         * 获取交易所Id
         */
        AppResult appResult = this.getUserID(userId);
        if (appResult.getStatus()==-1){
            return appResult;
        }
        String userID = appResult.getData().toString();
        String result = toolfeignInterface.getFunds(userID,coinId,page);
        if ("error".equals(result)){
            return AppResult.ERROR("调用熔断方法");
        }
        JSONObject jsonObject = JSON.parseObject(result);
        JSONArray rjsonArray = new JSONArray();
        if(jsonObject.getString("des").toString().equals("success")){
            JSONObject datas = jsonObject.getJSONObject("datas");
            JSONArray  jsonArray =  datas.getJSONArray("list");
            for(Object object:jsonArray){
                JSONObject jsonObject1 = (JSONObject) object;
                String billdate = jsonObject1.getString("billDate");
                SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");

                Date date = new Date(Long.parseLong(billdate));
                //date.getTime(Long.getLong(billdate));
                jsonObject1.put("billDate",format.format(date));
                rjsonArray.add(jsonObject1);

            }
            JSONObject  jsonObject1 = new JSONObject();
            jsonObject1.put("list",rjsonArray);
            return AppResult.OK(jsonObject1);
        }else{
            return AppResult.ERROR("获取列表失败!");
        }

    }
    @RequestMapping("/getRate")
    public AppResult getRate(){
        SysConfigs sysConfigs = new SysConfigs();
        sysConfigs.setFieldCode("hhtbRate");
        EntityWrapper<SysConfigs> entityWrapper = new EntityWrapper<SysConfigs>(sysConfigs);
        sysConfigs = sysConfigsService.selectOne(entityWrapper);
        BigDecimal rate  =  new BigDecimal(sysConfigs.getFieldValue());
        Map<String,Object> resultMap =new HashMap<>();
        BigDecimal  cashTohhtbRate=new BigDecimal(1).divide(rate,4,BigDecimal.ROUND_DOWN);
        resultMap.put("cashTohhtbRate",cashTohhtbRate);//RMB转HHTB
        String ticker = toolfeignInterface.ticker();
        BigDecimal tickerNew = new BigDecimal(ticker);//RMB 转MAOC定期
        BigDecimal hhtbtomaoc=(rate.multiply(tickerNew)).setScale(4,BigDecimal.ROUND_DOWN);
        resultMap.put("hhtbtomaoc",hhtbtomaoc);//HHTB转MAOC
        return   AppResult.OK(resultMap);
    }

    @RequestMapping("/hhtbToStatedcc")
    public AppResult hhtbToStatedcc(Integer userId,String hhtbNum){
        String result = null;
        int returnVal = accountService.hhtbToStatedcc(userId,hhtbNum);
        if(1==returnVal){
            result="操作成功！";
            return  AppResult.OK(result);
        }else if(2==returnVal){
            result="余额不足！";
        }else if(3==returnVal){
            result="请输入有效金额！";
        }else{
            result="系统异常！";
        }
        return   AppResult.ERROR(result);
    }

}
